import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/state/chat/kite_chat_controller.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import '../../utils/kudo_helper.dart';
import '../../utils/image_resource_helper.dart';
import '../../widget/report_dialog.dart';
import '../../router/app_navigation_manager.dart';
import '../../widget/login_required_dialog.dart';
import '../../state/person/persona_session_controller.dart';
import '../../state/person/persona_entity.dart';
import '../../state/exchange/kite_exchange_controller.dart';
import '../../state/exchange/kite_exchange_entity.dart';
import '../../state/exchange/kite_exchange_comment_entity.dart';

class KiteExchangeDetailScreen extends StatefulWidget {
  final KiteExchangeEntity exchangeData;

  const KiteExchangeDetailScreen({super.key, required this.exchangeData});

  @override
  State<KiteExchangeDetailScreen> createState() =>
      _KiteExchangeDetailScreenState();
}

class _KiteExchangeDetailScreenState extends State<KiteExchangeDetailScreen> {
  final TextEditingController _commentInputController = TextEditingController();
  final ReactiveValueNotifier<List<KiteExchangeCommentEntity>> _commentsState =
      ReactiveValueNotifier([]);

  @override
  void initState() {
    super.initState();
    _initializeExchangeData();
  }

  @override
  void dispose() {
    _commentInputController.dispose();
    super.dispose();
  }

  void _initializeExchangeData() {
    KiteExchangeController.globalInstance.selectExchange(
      widget.exchangeData.uniqueIdentifier,
    );
    _refreshCommentData();
  }

  void _refreshCommentData() {
    final comments = KiteExchangeController.globalInstance.getExchangeComments(
      widget.exchangeData.uniqueIdentifier,
    );
    _commentsState.value = comments;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/main_background.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Stack(
          children: [
            Column(
              children: [
                _constructTopNavigationBar(),
                SingleChildScrollView(
                  padding: EdgeInsets.only(bottom: 80.h),
                  child: [
                    _constructMediaDisplayContainer(),
                    _constructKiteInstructionsSection(),
                    _constructUserReviewSection(),
                  ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
                ).expanded(),
              ],
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: _constructBottomCommentInput(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _constructTopNavigationBar() {
    return Container(
      height: 100.h,
      padding: EdgeInsets.only(top: 44.h, left: 16.w, right: 16.w),
      child: Row(
        children: [
          Icon(
            Icons.arrow_back_ios_new,
            size: 20.sp,
            color: Colors.black,
          ).inkWell(onTap: () => GoRouter.of(context).pop()),

          Text(
            'Kite Exchange',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w900,
              color: Colors.black,
              fontFamily:
                  GoogleFonts.montserrat(
                    fontWeight: FontWeight.w900,
                  ).fontFamily,
            ),
            textAlign: TextAlign.center,
          ),

          const Spacer(),

          ImageResourceHelper.buildSvgIcon(
            svgPath: 'assets/svg/report.svg',
            width: 22.w,
            height: 22.h,
            color: KudoColors.black,
          ).inkWell(onTap: _displayExchangeReportDialog),
        ],
      ),
    );
  }

  Widget _constructMediaDisplayContainer() {
    final publisher = PersonaSessionController.quickGetUserById(
      widget.exchangeData.publisherPersonaId,
    );
    final isVideoContent = widget.exchangeData.mediaType == MediaType.video;

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      width: 343.w,
      height: 310.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20.r),
        image: DecorationImage(
          image: AssetImage(
            isVideoContent
                ? (widget.exchangeData.thumbnailResourceUrl ??
                    widget.exchangeData.mediaResourceUrl)
                : widget.exchangeData.mediaResourceUrl,
          ),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        children: [
          if (isVideoContent)
            Center(
              child: Container(
                width: 60.w,
                height: 60.h,
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.6),
                  borderRadius: BorderRadius.circular(30.r),
                ),
                child: Icon(Icons.play_arrow, color: Colors.white, size: 30.sp),
              ),
            ),

          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.transparent,
                    Colors.black.withValues(alpha: 0.7),
                  ],
                ),
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(20.r),
                  bottomRight: Radius.circular(20.r),
                ),
              ),
              padding: EdgeInsets.all(12.w),
              child: Row(
                children: [
                  [
                    GestureDetector(
                      onTap: () {
                        if (publisher != null) {
                          _handleUserAvatarTap(publisher);
                        }
                      },
                      child: CircleAvatar(
                        radius: 25.r,
                        backgroundImage: AssetImage(
                          publisher?.avatarResourceUrl ??
                              'assets/images/default_avatar.png',
                        ),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Text(publisher?.displayAlias ?? 'Unknown')
                        .fontSize(16.sp)
                        .fontWeight(FontWeight.w500)
                        .fontFamily(
                          GoogleFonts.lato(
                            fontWeight: FontWeight.w500,
                          ).fontFamily!,
                        )
                        .textColor(Colors.white)
                        .fontFamily(GoogleFonts.lato().fontFamily!),
                  ].toRow().expanded(),

                  Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          color: KudoColors.yellow,
                          borderRadius: BorderRadius.circular(11.r),
                        ),
                        child: Text('Exchange')
                            .fontSize(16.sp)
                            .fontWeight(FontWeight.w500)
                            .fontFamily(
                              GoogleFonts.lato(
                                fontWeight: FontWeight.w500,
                              ).fontFamily!,
                            )
                            .italic()
                            .textColor(Colors.black),
                      )
                      .configWidget(borderRadius: 11.r)
                      .inkWell(onTap: _handleExchangeButtonTap),
                ],
              ),
            ),
          ),
        ],
      ),
    ).inkWell(onTap: _handleMediaContainerTap);
  }

  Widget _constructKiteInstructionsSection() {
    return [
          Text('Kite instructions')
              .fontSize(20.sp)
              .fontWeight(FontWeight.w700)
              .textColor(KudoColors.black)
              .fontFamily(
                GoogleFonts.lato(fontWeight: FontWeight.w700).fontFamily!,
              ),

          SizedBox(height: 12.h),

          Container(
            width: double.infinity,
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: KudoColors.green,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Text(widget.exchangeData.exchangeDescription)
                .fontSize(15.sp)
                .textColor(KudoColors.black)
                .fontFamily(
                  GoogleFonts.lato(fontWeight: FontWeight.w600).fontFamily!,
                ),
          ).configWidget(borderRadius: 20.r),
        ]
        .toColumn(crossAxisAlignment: CrossAxisAlignment.start)
        .paddingHorizontal(16.w);
  }

  Widget _constructUserReviewSection() {
    return [
          SizedBox(height: 24.h),

          Text(
            'User Review',
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.w700,
              color: Colors.black,
              fontFamily:
                  GoogleFonts.lato(fontWeight: FontWeight.w700).fontFamily,
            ),
            textAlign: TextAlign.center,
          ),

          SizedBox(height: 16.h),

          _commentsState.reactiveValue(context).isNotEmpty
              ? Column(
                children:
                    _commentsState.value
                        .map((comment) => _constructCommentItem(comment))
                        .toList(),
              )
              : SizedBox(
                height: 100.h,
                child: Center(
                  child: Text(
                    'No comments yet',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ),
              ),
        ]
        .toColumn(crossAxisAlignment: CrossAxisAlignment.start)
        .paddingHorizontal(16.w);
  }

  Widget _constructCommentItem(KiteExchangeCommentEntity comment) {
    final commenter = PersonaSessionController.quickGetUserById(
      comment.commenterPersonaId,
    );

    return Container(
          padding: EdgeInsets.all(12.w),
          decoration: BoxDecoration(
            color: KudoColors.black,
            borderRadius: BorderRadius.circular(20.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: [
            Row(
              children: [
                [
                  GestureDetector(
                    onTap: () {
                      if (commenter != null) {
                        _handleUserAvatarTap(commenter);
                      }
                    },
                    child: CircleAvatar(
                      radius: 17.r,
                      backgroundImage: AssetImage(
                        commenter?.avatarResourceUrl ??
                            'assets/images/default_avatar.png',
                      ),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Text(commenter?.displayAlias ?? 'Unknown')
                      .fontSize(14.sp)
                      .fontWeight(FontWeight.w700)
                      .textColor(Colors.white)
                      .fontFamily(
                        GoogleFonts.lato(
                          fontWeight: FontWeight.w700,
                        ).fontFamily!,
                      ),
                ].toRow().expanded(),

                ImageResourceHelper.buildSvgIcon(
                  svgPath: 'assets/svg/report.svg',
                  width: 20.w,
                  height: 20.h,
                  color: Colors.white,
                ).inkWell(onTap: () => _displayCommentReportDialog(comment)),
              ],
            ),

            SizedBox(height: 8.h),

            Text(comment.commentTextContent)
                .fontSize(13.sp)
                .textColor(Colors.white)
                .fontFamily(GoogleFonts.lato().fontFamily!),
          ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
        )
        .configWidget(borderRadius: 20.r, color: KudoColors.yellow)
        .paddingBottom(12.h);
  }

  Widget _constructBottomCommentInput() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),

      decoration: BoxDecoration(color: Colors.transparent),
      child: Container(
        height: 50.h,
        decoration: BoxDecoration(
          color: KudoColors.yellow,
          borderRadius: BorderRadius.circular(100.r),
        ),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: _commentInputController,
                decoration: InputDecoration(
                  hintText: 'Add a comment...',
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 12.h,
                  ),
                  hintStyle: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey.shade600,
                  ),
                ),
                style: TextStyle(fontSize: 14.sp),
              ),
            ),

            Container(
              width: 40.w,
              height: 40.w,
              margin: EdgeInsets.only(right: 6.w),
              decoration: BoxDecoration(
                color: KudoColors.black,
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: ImageResourceHelper.buildSvgIcon(
                svgPath: 'assets/svg/send.svg',
                width: 16.w,
                height: 16.w,
                color: KudoColors.yellow,
              ),
            ).inkWell(onTap: _handleCommentSubmission),
          ],
        ),
      ).configWidget(borderRadius: 100.r),
    );
  }

  void _handleExchangeButtonTap() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;

    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'You need to login to start a chat',
      );
      return;
    }

    if (currentUser.uniqueIdentifier ==
        widget.exchangeData.publisherPersonaId) {
      KudoToast.showErrorToast(context, 'You cannot chat with yourself');
      return;
    }

    final chatSession = KiteChatController.globalInstance
        .getOrCreateSessionWithUser(widget.exchangeData.publisherPersonaId);
    if (chatSession != null) {
      AppNavigationManager.navigateToKitePrivateChat(context, chatSession);
    }
  }

  void _handleMediaContainerTap() {
    if (widget.exchangeData.mediaType == MediaType.video) {
      AppNavigationManager.navigateToKiteVideoPlayer(
        context,
        widget.exchangeData.mediaResourceUrl,
      );
    }
  }

  void _handleCommentSubmission() {
    final commentText = _commentInputController.text.trim();
    if (commentText.isEmpty) return;

    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to comment',
      );
      return;
    }

    final success = KiteExchangeController.globalInstance
        .publishExchangeComment(
          exchangeId: widget.exchangeData.uniqueIdentifier,
          commentContent: commentText,
        );

    if (success) {
      _commentInputController.clear();
      _refreshCommentData();
      KudoToast.showSuccessToast(context, 'Comment posted successfully');
    } else {
      KudoToast.showErrorToast(context, 'Failed to post comment');
    }
  }

  void _displayExchangeReportDialog() {
    ReportDialog.show(
      context: context,
      title: 'Report Kite Exchange',
      onReport: (reportType) {
        final success = KiteExchangeController.quickDeleteExchange(
          widget.exchangeData.uniqueIdentifier,
        );
        if (success) {
          KudoToast.showSuccessToast(context, 'Exchange reported successfully');
          Navigator.of(context).pop();
        } else {
          KudoToast.showErrorToast(context, 'Failed to report exchange');
        }
      },
    );
  }

  void _displayCommentReportDialog(KiteExchangeCommentEntity comment) {
    ReportDialog.show(
      context: context,
      title: 'Report Comment',
      onReport: (reportType) {
        final success = KiteExchangeController.globalInstance
            .deleteExchangeComment(comment.uniqueIdentifier);
        if (success) {
          _refreshCommentData();
          KudoToast.showSuccessToast(context, 'Comment reported successfully');
        } else {
          KudoToast.showErrorToast(context, 'Failed to report comment');
        }
      },
    );
  }

  void _handleUserAvatarTap(PersonaEntity user) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;

    if (currentUser != null &&
        currentUser.uniqueIdentifier == user.uniqueIdentifier) {
      return;
    }

    AppNavigationManager.navigateToOtherPersonaScreen(context, user);
  }
}
